Chapter 03: Random effect logistic-regression¶
1. Introduction¶
In this chapter, we will analyze the experimental data using Bayesian Analysis, and the inference will be carried out in Pyro. The organization of the notebook is inspired from Bayesian Workflow by Prof. Andrew Gelman et al. Another piece of work in that direction is from Betancourt et al here. However, the current analysis is a WIP and far from perfect.
An almost always first step in Bayesian Analysis is to elicit a plausible generative model, that would have likely generated the observed data. In this case, consider the model suggesed/implemented in WinBUGs Vol1.
We want to model the relationship between avoidance-in-future and past-traumatic-experiences . The following log-linear model is a starting point:
\(\pi_j = A^{xj} B^{j-xj} \)
where :
\(\pi_j\) is the probability of a dog getting shocked at trial \(j\)
\(x_j\) is number of successful avoidances of shock prior to trial \(j\).
\(j-x_j\) is number of shocks experienced prior to trial \(j\).
A & B, both are unknown and treated as random variables.
However, the model is only partially complete. In a Bayesian setting, we need to elicit our prior beliefs about the unknowns. Consequently, we need to give priors to \(A\) and \(B\), which we do shortly. Before that, we need some boiler plate code, mostly imports. Note that, all the code (functions) are glued in the base class. If one is interested, they can always browse the code repo to get better understanding.
import torch
import pyro
import pandas as pd
import itertools
from collections import defaultdict
import matplotlib.pyplot as plt
import pyro.distributions as dist
import seaborn as sns
import plotly
import plotly.express as px
import plotly.figure_factory as ff
from chapter01 import base
import numpy as np
pyro.set_rng_seed(1)
plt.style.use('default')
%matplotlib inline
%load_ext autoreload
Data¶
The data contains experiments over 30 dogs, each dog is subjected to 25 trials.
The plot that follows highlights Dogs data in dictionary format, averaged over dog population for each trial.
write latex for summation of averaged over dog population for each trial.
lsat_data = base.load_data()
# lsat_data
# base.plot_original_y(np.mean(dogs_data["Y"], axis=0), ylabel='Probability of avoidance at trial j')
N <- 1000
R <- 32
T <- 5
culm <- c(3, 9, 11, 22, 23, 24, 27, 31, 32, 40, 40, 56, 56, 59, 61, 76, 86, 115, 129, 210, 213, 241, 256, 336, 352, 408, 429, 602, 613, 674, 702, 1000)
"response" <-
structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0,
0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0,
1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1), .Dim = c(32,
5))
{'Ndogs': 30,
'Ntrials': 25,
'Y': array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0],
[0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0,
0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1,
0, 1, 1],
[0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0,
0, 0, 0],
[1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0,
1, 1, 0],
[1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1,
0, 1, 0],
[1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0,
1, 0, 1],
[0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0,
1, 0, 1],
[1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1,
1, 1, 0],
[1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1,
1, 0, 1],
[1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0,
0, 1, 1],
[1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1],
[1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1]])}
??base.DogsModel
Its apparent from experimental data that more than half the dog population learns to avoid shocks in trials as few as 5, and also that the learning doesn’t significantly rise with increased number of trials.
Preprocessing¶
Following transforms target label Y to obtain input data x_avoidance, x_shocked & y where:
x_avoidance: number of shock avoidances before current trial.x_shocked: number of shocks before current trial.y: Status ‘shocked or avoided’ at current trial.
Here pystan format data (python dictionary) is passed to the function above, in order to preprocess it to tensor format required for pyro sampling.
x_avoidance, x_shocked, y = base.transform_data(**dogs_data)
print("x_avoidance: %s, x_shocked: %s, y: %s"%(x_avoidance.shape, x_shocked.shape, y.shape))
print("\nSample x_avoidance: %s \n\nSample x_shocked: %s"%(x_avoidance[1], x_shocked[1]))
base.plot_original_y(x_avoidance.numpy(), ylabel='Cumulative Avoidances')
base.plot_original_y(x_shocked.numpy(), ylabel='Cumulative Shocked Trials')
x_avoidance: torch.Size([30, 25]), x_shocked: torch.Size([30, 25]), y: torch.Size([30, 25])
Sample x_avoidance: tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 1., 2., 2., 3.])
Sample x_shocked: tensor([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 8., 9., 10., 11., 12.,
13., 14., 15., 16., 17., 18., 19., 20., 20., 21., 21.])
The original data is not revealing much, looking at the cumulative avoidances and shocks, we see that some dogs never learn (example: Dog 1-4), and some dogs learn and retain the learning behaviour (example: Dog 25-30).
2. Model Specification¶
The sampling distrution of the generative model, as indicated earlier, is:
\(y_{ij} \sim Bern(\pi_{ij})\)
\(\log(\pi_{ij}) = \alpha x_{ij} + \beta({j-x_{ij}})\)
Here, \(y_{ij}=1\) if the a dog fails to avoid a shock at the j-th trial, and is 0 if it avoids. We elicit normal priors for \(\alpha,\beta\) with zero mean and large variance (flat) to complete the specification. Also notice that, the above model is in a more familiar form (Generalized Linear Model or Log-Linear Model). For convenience, we can define \(X_{a}\equiv x_{ij}, X_{s}\equiv j-x_{ij} \)
The complete model is:
\(y_{ij} \sim Bern(\pi_{ij})\)
\(\log(\pi_{ij}) = \alpha X_{a} + \beta X_{s}\)
\(\alpha \sim N(0., 316.)\)
\(\beta \sim N(0., 316.)\)
The above expression is used as a generalised linear model with log-link function in WinBugs implementation
BUGS model¶
\(\log\pi_j = \alpha\ x_j + \beta\ ( \)j\(-x_j )\)
Here
\(\log\pi_j\) is log probability of a dog getting shocked at trial \(j\)
\(x_j\) is number of successful avoidances of shock prior to trial \(j\).
\(j-x_j\) is number of shocks experienced prior to trial \(j\).
\(\alpha\) is the coefficient corresponding to number of successes, \(\beta\) is the coefficient corresponding to number of failures.
Following code block is from original BUGS volume:
{
for (i in 1 : Dogs) {
xa[i, 1] <- 0; xs[i, 1] <- 0 p[i, 1] <- 0
for (j in 2 : Trials) {
xa[i, j] <- sum(Y[i, 1 : j - 1])
xs[i, j] <- j - 1 - xa[i, j]
log(p[i, j]) <- alpha * xa[i, j] + beta * xs[i, j]
y[i, j] <- 1 - Y[i, j]
y[i, j] ~ dbern(p[i, j])
}
}
alpha ~ dnorm(0, 0.00001)I(, -0.00001)
beta ~ dnorm(0, 0.00001)I(, -0.00001)
A <- exp(alpha)
B <- exp(beta)
}
The same model when implemented in PyStan
Equivalent Stan model¶
{
alpha ~ normal(0.0, 316.2);
beta ~ normal(0.0, 316.2);
for(dog in 1:Ndogs)
for (trial in 2:Ntrials)
y[dog, trial] ~ bernoulli(exp(alpha * xa[dog, trial] + beta * xs[dog, trial]));
}
data {
int<lower=0> N; // 1000, number of students
int<lower=0> R; // 32, number of patterns of results: 2^T
int<lower=0> T; // 5, number of questions
int<lower=0> culm[R];
int<lower=0> response[R,T];
}
transformed data {a
int r[T,N];
vector[N] ones;
for (j in 1:culm[1]) {
for (k in 1:T) {
r[k,j] <- response[1,k];
}
}
for (i in 2:R) {
for (j in (culm[i-1] + 1):culm[i]) {
for (k in 1:T) {
r[k,j] <- response[i,k];
}
}
}
for (i in 1:N)
ones[i] <- 1.0;
}
parameters {
real alpha[T];
vector[N] theta;
real<lower=0> beta;
}
model {
alpha ~ normal(0, 100.);
theta ~ normal(0, 1);
beta ~ normal(0.0, 100.);
for(k in 1:T)
r[k] ~ bernoulli_logit(beta * theta - alpha[k] * ones);
}
generated quantities {
real mean_alpha;
real a[T];
mean_alpha <- mean(alpha);
for(t in 1:T) a[t] <- alpha[t] - mean_alpha;
}
Model implementation¶
The above model is defined in base.DogsModel
DogsModel= base.DogsModel
DogsModel
<function chapter01.base.DogsModel(x_avoidance, x_shocked, y)>
Let us also draw few samples from the prior, and look at the distribution
num_samples = 1100
priors_list= [(pyro.sample("alpha", dist.Normal(0., 316.)).item(),
pyro.sample("beta", dist.Normal(0., 316.)).item()) for index in range(num_samples)]# Picking 1100 prior samples
prior_samples = {"alpha":list(map(lambda prior_pair:prior_pair[0], priors_list)), "beta":list(map(lambda prior_pair:prior_pair[1], priors_list))}
Sampled output of prior values for alpha & beta is stored in prior_samples above, and is plotted on a KDE plot as follows:
fig = ff.create_distplot(list(prior_samples.values()), list(prior_samples.keys()))
fig.update_layout(title="Prior distribution of parameters", xaxis_title="parameter values", yaxis_title="density", legend_title="parameters")
fig.show()
print("Prior alpha Q(0.5) :%s | Prior beta Q(0.5) :%s"%(np.quantile(prior_samples["alpha"], 0.5), np.quantile(prior_samples["beta"], 0.5)))
Prior alpha Q(0.5) :2.7043710947036743 | Prior beta Q(0.5) :-15.45756196975708
3. Prior predictive checking¶
parameters_pairs = list(zip(*list(prior_samples.values())))
print("total samples count:", len(parameters_pairs), " sample example: ", parameters_pairs[:2])
simulated_data_given_pair= base.simulate_observations_given_param(init_obs=0, num_dogs=30, num_trials=24, parameter_pair_list= parameters_pairs)#, print_logs=1
print("Number of datasets/prior pairs generated: ", simulated_data_given_pair.shape[0])
total samples count: 1100 sample example: [(208.98727416992188, 84.3480224609375), (19.490013122558594, 196.33627319335938)]
/Users/tachyon/Desktop/p3/Part_II/Chapter_1/chapter01.py:187: RuntimeWarning:
overflow encountered in exp
Total execution time: 72.64989995956421
Number of datasets/prior pairs generated: 1100
simulated_data_given_pair_flattened = np.reshape(simulated_data_given_pair, (-1, 25))
arr1 = np.mean(dogs_data["Y"], axis=0)
arr2=np.mean(simulated_data_given_pair_flattened, axis=0)
original_plus_simulated_data= np.concatenate([arr1.reshape((1, -1)), arr2.reshape((1, -1))])
print("respective shapes of original data: %s, data simulated from prior: %s and concatenated arrays: %s"%(arr1.shape, arr2.shape, original_plus_simulated_data.shape))
respective shapes of original data: (25,), data simulated from prior: (25,) and concatenated arrays: (2, 25)
base.plot_original_y(original_plus_simulated_data, ylabel='Probability of avoidance at trial j [Both original & simulated prior data]')
print("Here 'Dog 1' corresponds to Original data & 'Dog 2' corresponds to data simulated from prior")
Here 'Dog 1' corresponds to Original data & 'Dog 2' corresponds to data simulated from prior
Even though the mean and median can differ from run to run, looking at the densities, the variance is vary large – so the sample mean would also have huge variance. The take-away is that, both \(\alpha, \beta\) are given very weak priors. We more or less rely on the data (evidence) to drive their estimation.
TBD: Prior Sensitivity Analysis
4. Posterior Estimation¶
In the Bayesian setting, inference is drawn from the posterior. Here, posterior implies the updated beliefs about the random variables, in the wake of given evidences (data). Formally,
\(Posterior = \frac {Likelihood x Prior}{Probability \ of Evidence}\)
In our case, \(\alpha,\beta\) are the parameters (actually random variables) & \(y\) is the evidence; Posterior \(P(\alpha,\beta | y)\) is given, according to the Bayes rule, as:
\(P\ (\alpha,\beta | y) = \frac {P(y | \alpha,\beta) \pi(\alpha,\beta)}{P(y)}\)
Now our interest is in estimating the posterior summaries of the parameters \(\alpha, \beta\). For example, we can look at the posterior of mean of \(\alpha\), denoted as \(E(\alpha)\). However, in order to the get the posterior quanitities, either we need to compute the integrals or approximate the integrals via Markov Chain Monte Carlo.
The latter can be easily accomplished in Pyro by using the NUTS sampler – NUTS is a specific sampler designed to draw samples efficiently from the posterior using Hamiltonian Monte Carlo dynamics.
The following code snippet takes a pyro model object with posterior specification, input data, some configuration parameters such as a number of chains and number of samples per chain. It then laucnhes a NUTS sampler and produces MCMC samples in a python dictionary format.
hmc_sample_chains, hmc_chain_diagnostics = base.get_hmc_n_chains(DogsModel, x_avoidance, x_shocked, y, num_chains=4, sample_count = 900)
Sample: 100%|██████████| 10090/10090 [00:42, 236.99it/s, step size=5.73e-01, acc. prob=0.914]
Sample: 100%|██████████| 10090/10090 [01:04, 157.51it/s, step size=1.99e-02, acc. prob=0.975]
Sample: 15%|█▌ | 1541/10090 [06:18, 1.53it/s, step size=2.37e-03, acc. prob=0.806]
# import time
# from collections import defaultdict
# from scipy import stats
# import pyro.distributions as dist
# from torch import nn
# from pyro.nn import PyroModule
# from pyro.infer import MCMC, NUTS
# # model with Pij as sigmoid()
# hmc_sample_chains, hmc_chain_diagnostics = base.get_hmc_n_chains(DogsModel, x_avoidance, x_shocked, y, num_chains=2, sample_count = 900)
Sample: 100%|██████████| 10090/10090 [00:39, 255.33it/s, step size=5.73e-01, acc. prob=0.914]
Sample: 100%|██████████| 10090/10090 [08:33, 19.65it/s, step size=1.99e-02, acc. prob=0.975]
Total time: 553.4843950271606
# ??base.get_hmc_n_chains
DogsModel= base.DogsModel
??DogsModel
# def DogsModel(x_avoidance, x_shocked, y):
# """
# Input
# -------
# x_avoidance: tensor holding avoidance count for all dogs & all trials, example for
# 30 dogs & 25 trials, shaped (30, 25)
# x_shocked: tensor holding shock count for all dogs & all trials, example for 30 dogs
# & 25 trials, shaped (30, 25).
# y: tensor holding response for all dogs & trials, example for 30 dogs
# & 25 trials, shaped (30, 25).
# Output
# --------
# Implements pystan model: {
# alpha ~ normal(0.0, 316.2);
# beta ~ normal(0.0, 316.2);
# for(dog in 1:Ndogs)
# for (trial in 2:Ntrials)
# y[dog, trial] ~ bernoulli(exp(alpha * xa[dog, trial] + beta * xs[dog, trial]));}
# """
# sigmoid = lambda value: 1/(1+torch.exp(-value))
# alpha = pyro.sample("alpha", dist.Normal(0., 316.))
# beta = pyro.sample("beta", dist.Normal(0., 316))
# with pyro.plate("data"):
# pyro.sample("obs", dist.Bernoulli(torch.exp(alpha*x_avoidance + beta * x_shocked)), obs=y)
# dist.Bernoulli(torch.exp(torch.tensor(559.0206) + torch.tensor(60.4276)))
torch.exp(torch.tensor(559.0206) + torch.tensor(60.4276))
tensor(inf)
sigmoid = lambda value: 1/(1+np.exp(-value))
plt.plot(np.random.normal(0, 316, 10000))
[<matplotlib.lines.Line2D at 0x7f8605ca9310>]
# # list(map(lambda x:x.numpy(), samples.values()))
# # base_expression = lambda alpha, beta :
# arr1= sigmoid(np.random.normal(0, 316, 10000))
# arr2= sigmoid(np.random.uniform(-30, 30, 10000))
# # arr3 = np.exp(np.random.normal(0, 316, 10000))
# # arr4 = np.exp(np.random.uniform(-30, 30, 10000))
<ipython-input-16-790daf6b7f09>:1: RuntimeWarning:
overflow encountered in exp
<ipython-input-29-0a2cd88006af>:6: RuntimeWarning:
overflow encountered in exp
# title= "parameter distribution for : chain"
# fig = ff.create_distplot([arr1, arr2], ["normal_sigmoid", "uniform_sigmoid"])#list(map(lambda x:x.numpy(), samples.values())), list(samples.keys()))
# # fig = ff.create_distplot([arr1, arr2, arr3, arr4], ["normal_sigmoid", "uniform_sigmoid", "normal_exp", "uniform_exp"])#list(map(lambda x:x.numpy(), samples.values())), list(samples.keys()))
# fig.update_layout(title=title, xaxis_title="parameter values", yaxis_title="density", legend_title="parameters")
# fig.show()
# for i in range(500):
# alpha = pyro.sample("alpha", dist.Normal(0., 316.))
# beta = pyro.sample("beta", dist.Normal(0., 316))
# print("index: %s | alpha: %s | beta: %s"%(i, alpha, beta))
index: 0 | alpha: tensor(-169.7478) | beta: tensor(-153.3592)
index: 1 | alpha: tensor(-109.0383) | beta: tensor(174.6022)
index: 2 | alpha: tensor(102.4450) | beta: tensor(-470.9258)
index: 3 | alpha: tensor(-106.3998) | beta: tensor(-791.8300)
index: 4 | alpha: tensor(294.0310) | beta: tensor(-117.5779)
index: 5 | alpha: tensor(477.4664) | beta: tensor(-87.5307)
index: 6 | alpha: tensor(-312.2924) | beta: tensor(-149.4893)
index: 7 | alpha: tensor(225.6406) | beta: tensor(-304.8745)
index: 8 | alpha: tensor(97.7954) | beta: tensor(-113.9791)
index: 9 | alpha: tensor(149.0742) | beta: tensor(-444.8320)
index: 10 | alpha: tensor(-496.5970) | beta: tensor(962.9677)
index: 11 | alpha: tensor(-700.2028) | beta: tensor(120.5167)
index: 12 | alpha: tensor(-76.0722) | beta: tensor(-556.5853)
index: 13 | alpha: tensor(-436.3638) | beta: tensor(354.2415)
index: 14 | alpha: tensor(425.1484) | beta: tensor(-462.2254)
index: 15 | alpha: tensor(459.8388) | beta: tensor(292.6935)
index: 16 | alpha: tensor(479.1924) | beta: tensor(-160.7785)
index: 17 | alpha: tensor(-365.0735) | beta: tensor(-256.5266)
index: 18 | alpha: tensor(-170.4264) | beta: tensor(-248.2440)
index: 19 | alpha: tensor(384.8474) | beta: tensor(-121.5427)
index: 20 | alpha: tensor(334.1027) | beta: tensor(190.6751)
index: 21 | alpha: tensor(-627.7797) | beta: tensor(135.9207)
index: 22 | alpha: tensor(463.2754) | beta: tensor(-265.5546)
index: 23 | alpha: tensor(-643.2644) | beta: tensor(684.2418)
index: 24 | alpha: tensor(-104.2892) | beta: tensor(-657.9000)
index: 25 | alpha: tensor(-50.6990) | beta: tensor(-35.6896)
index: 26 | alpha: tensor(-238.2332) | beta: tensor(299.4866)
index: 27 | alpha: tensor(-395.3108) | beta: tensor(363.8985)
index: 28 | alpha: tensor(-163.1378) | beta: tensor(-226.9219)
index: 29 | alpha: tensor(-67.6979) | beta: tensor(6.7917)
index: 30 | alpha: tensor(297.3091) | beta: tensor(-93.3429)
index: 31 | alpha: tensor(328.1287) | beta: tensor(32.9020)
index: 32 | alpha: tensor(82.1597) | beta: tensor(-60.5275)
index: 33 | alpha: tensor(46.8679) | beta: tensor(-97.9654)
index: 34 | alpha: tensor(-175.3800) | beta: tensor(59.1878)
index: 35 | alpha: tensor(286.3033) | beta: tensor(-416.5889)
index: 36 | alpha: tensor(279.5056) | beta: tensor(-183.8273)
index: 37 | alpha: tensor(-244.9786) | beta: tensor(-9.8569)
index: 38 | alpha: tensor(62.5392) | beta: tensor(23.2321)
index: 39 | alpha: tensor(-42.3645) | beta: tensor(246.4574)
index: 40 | alpha: tensor(-33.3556) | beta: tensor(-343.4033)
index: 41 | alpha: tensor(376.7575) | beta: tensor(116.1259)
index: 42 | alpha: tensor(-212.6320) | beta: tensor(-95.5476)
index: 43 | alpha: tensor(-478.3601) | beta: tensor(156.7800)
index: 44 | alpha: tensor(-351.6765) | beta: tensor(-163.0629)
index: 45 | alpha: tensor(-239.9228) | beta: tensor(-103.3261)
index: 46 | alpha: tensor(-169.1570) | beta: tensor(-7.5874)
index: 47 | alpha: tensor(-480.3336) | beta: tensor(219.1866)
index: 48 | alpha: tensor(-220.8731) | beta: tensor(43.7018)
index: 49 | alpha: tensor(559.0206) | beta: tensor(60.4276)
index: 50 | alpha: tensor(-540.8492) | beta: tensor(-113.8262)
index: 51 | alpha: tensor(-261.2458) | beta: tensor(96.6112)
index: 52 | alpha: tensor(-530.9393) | beta: tensor(606.4276)
index: 53 | alpha: tensor(-99.8747) | beta: tensor(-187.4090)
index: 54 | alpha: tensor(359.0257) | beta: tensor(-329.2057)
index: 55 | alpha: tensor(-235.6044) | beta: tensor(-641.3134)
index: 56 | alpha: tensor(-215.4924) | beta: tensor(-136.8847)
index: 57 | alpha: tensor(-37.3948) | beta: tensor(-66.5956)
index: 58 | alpha: tensor(-19.6185) | beta: tensor(374.5669)
index: 59 | alpha: tensor(-544.9677) | beta: tensor(-591.4866)
index: 60 | alpha: tensor(-72.9364) | beta: tensor(-267.4087)
index: 61 | alpha: tensor(281.9507) | beta: tensor(159.5740)
index: 62 | alpha: tensor(-388.2271) | beta: tensor(221.3690)
index: 63 | alpha: tensor(-423.3959) | beta: tensor(-255.0217)
index: 64 | alpha: tensor(128.4347) | beta: tensor(-10.1053)
index: 65 | alpha: tensor(-17.8065) | beta: tensor(-196.0316)
index: 66 | alpha: tensor(-365.4331) | beta: tensor(339.0602)
index: 67 | alpha: tensor(31.1637) | beta: tensor(-624.5674)
index: 68 | alpha: tensor(352.1635) | beta: tensor(-60.8006)
index: 69 | alpha: tensor(-594.3270) | beta: tensor(-171.5428)
index: 70 | alpha: tensor(-390.5630) | beta: tensor(262.6228)
index: 71 | alpha: tensor(329.6244) | beta: tensor(-284.9282)
index: 72 | alpha: tensor(-27.1397) | beta: tensor(443.3870)
index: 73 | alpha: tensor(-294.6511) | beta: tensor(-197.8445)
index: 74 | alpha: tensor(245.9114) | beta: tensor(288.4785)
index: 75 | alpha: tensor(-27.7090) | beta: tensor(-166.5236)
index: 76 | alpha: tensor(-232.2041) | beta: tensor(-58.8673)
index: 77 | alpha: tensor(283.2111) | beta: tensor(-60.9449)
index: 78 | alpha: tensor(-178.6798) | beta: tensor(-72.3677)
index: 79 | alpha: tensor(489.9182) | beta: tensor(-419.4750)
index: 80 | alpha: tensor(530.8283) | beta: tensor(593.4148)
index: 81 | alpha: tensor(177.0904) | beta: tensor(37.2095)
index: 82 | alpha: tensor(-405.1532) | beta: tensor(-94.6756)
index: 83 | alpha: tensor(561.2507) | beta: tensor(51.7619)
index: 84 | alpha: tensor(-440.2065) | beta: tensor(-40.1895)
index: 85 | alpha: tensor(-281.2761) | beta: tensor(-235.8704)
index: 86 | alpha: tensor(159.5686) | beta: tensor(-196.1875)
index: 87 | alpha: tensor(110.7457) | beta: tensor(-18.3428)
index: 88 | alpha: tensor(257.3239) | beta: tensor(-187.2180)
index: 89 | alpha: tensor(-417.7649) | beta: tensor(4.9764)
index: 90 | alpha: tensor(231.5241) | beta: tensor(-316.1374)
index: 91 | alpha: tensor(136.1232) | beta: tensor(180.4359)
index: 92 | alpha: tensor(-540.3209) | beta: tensor(-403.4686)
index: 93 | alpha: tensor(211.2644) | beta: tensor(319.3973)
index: 94 | alpha: tensor(394.4718) | beta: tensor(-20.7965)
index: 95 | alpha: tensor(-314.8761) | beta: tensor(-225.4988)
index: 96 | alpha: tensor(239.5452) | beta: tensor(241.3558)
index: 97 | alpha: tensor(-110.3301) | beta: tensor(-176.9520)
index: 98 | alpha: tensor(345.4871) | beta: tensor(-322.9639)
index: 99 | alpha: tensor(-510.5463) | beta: tensor(-728.8788)
index: 100 | alpha: tensor(-181.2037) | beta: tensor(-111.7355)
index: 101 | alpha: tensor(-45.0211) | beta: tensor(-556.4877)
index: 102 | alpha: tensor(143.0921) | beta: tensor(-664.0916)
index: 103 | alpha: tensor(-789.7107) | beta: tensor(316.3322)
index: 104 | alpha: tensor(25.6436) | beta: tensor(-301.4581)
index: 105 | alpha: tensor(-641.7161) | beta: tensor(329.4494)
index: 106 | alpha: tensor(96.6656) | beta: tensor(-214.4484)
index: 107 | alpha: tensor(434.7892) | beta: tensor(-218.9861)
index: 108 | alpha: tensor(143.6337) | beta: tensor(-259.1870)
index: 109 | alpha: tensor(25.3721) | beta: tensor(-745.8730)
index: 110 | alpha: tensor(389.8983) | beta: tensor(-162.3119)
index: 111 | alpha: tensor(563.4136) | beta: tensor(-69.9680)
index: 112 | alpha: tensor(14.5992) | beta: tensor(-28.7801)
index: 113 | alpha: tensor(205.4144) | beta: tensor(21.3770)
index: 114 | alpha: tensor(-632.3764) | beta: tensor(-239.3017)
index: 115 | alpha: tensor(-285.6541) | beta: tensor(257.9377)
index: 116 | alpha: tensor(-146.6281) | beta: tensor(-66.5799)
index: 117 | alpha: tensor(-150.0531) | beta: tensor(594.0769)
index: 118 | alpha: tensor(374.7710) | beta: tensor(-213.4457)
index: 119 | alpha: tensor(7.0368) | beta: tensor(-25.8817)
index: 120 | alpha: tensor(-165.1498) | beta: tensor(-445.5938)
index: 121 | alpha: tensor(-573.1751) | beta: tensor(52.2177)
index: 122 | alpha: tensor(128.6102) | beta: tensor(761.5126)
index: 123 | alpha: tensor(-571.9313) | beta: tensor(-83.8317)
index: 124 | alpha: tensor(-193.1106) | beta: tensor(-222.3311)
index: 125 | alpha: tensor(640.1259) | beta: tensor(-53.9751)
index: 126 | alpha: tensor(-48.9732) | beta: tensor(316.9766)
index: 127 | alpha: tensor(-121.1646) | beta: tensor(269.2268)
index: 128 | alpha: tensor(-9.7223) | beta: tensor(-131.4737)
index: 129 | alpha: tensor(-523.7367) | beta: tensor(-16.7993)
index: 130 | alpha: tensor(287.7108) | beta: tensor(-37.4484)
index: 131 | alpha: tensor(268.2097) | beta: tensor(-23.4372)
index: 132 | alpha: tensor(-548.3477) | beta: tensor(-106.2050)
index: 133 | alpha: tensor(8.4756) | beta: tensor(14.6052)
index: 134 | alpha: tensor(723.2272) | beta: tensor(-440.1536)
index: 135 | alpha: tensor(-350.0771) | beta: tensor(-219.0251)
index: 136 | alpha: tensor(-309.2149) | beta: tensor(18.6686)
index: 137 | alpha: tensor(-44.2156) | beta: tensor(-41.5939)
index: 138 | alpha: tensor(-534.6510) | beta: tensor(-244.5110)
index: 139 | alpha: tensor(917.2513) | beta: tensor(-10.1953)
index: 140 | alpha: tensor(-106.0324) | beta: tensor(-417.7274)
index: 141 | alpha: tensor(-110.7376) | beta: tensor(-146.5510)
index: 142 | alpha: tensor(-249.1375) | beta: tensor(-1.1967)
index: 143 | alpha: tensor(154.5487) | beta: tensor(-406.4559)
index: 144 | alpha: tensor(456.1118) | beta: tensor(267.4160)
index: 145 | alpha: tensor(300.2522) | beta: tensor(330.7611)
index: 146 | alpha: tensor(-121.3027) | beta: tensor(-345.2554)
index: 147 | alpha: tensor(-255.1817) | beta: tensor(173.4605)
index: 148 | alpha: tensor(-156.0954) | beta: tensor(6.1832)
index: 149 | alpha: tensor(356.6796) | beta: tensor(178.0155)
index: 150 | alpha: tensor(-110.9527) | beta: tensor(7.0983)
index: 151 | alpha: tensor(-371.7967) | beta: tensor(-422.9466)
index: 152 | alpha: tensor(511.7946) | beta: tensor(-690.1265)
index: 153 | alpha: tensor(-39.3612) | beta: tensor(-260.7975)
index: 154 | alpha: tensor(340.8853) | beta: tensor(251.5404)
index: 155 | alpha: tensor(175.9823) | beta: tensor(274.2113)
index: 156 | alpha: tensor(-739.3494) | beta: tensor(-157.6702)
index: 157 | alpha: tensor(-321.5167) | beta: tensor(-381.8194)
index: 158 | alpha: tensor(376.9748) | beta: tensor(172.8127)
index: 159 | alpha: tensor(49.4456) | beta: tensor(133.3876)
index: 160 | alpha: tensor(195.9377) | beta: tensor(-304.2572)
index: 161 | alpha: tensor(-300.5984) | beta: tensor(-113.0464)
index: 162 | alpha: tensor(640.1114) | beta: tensor(-185.1623)
index: 163 | alpha: tensor(67.9027) | beta: tensor(259.5737)
index: 164 | alpha: tensor(-165.9656) | beta: tensor(-149.7473)
index: 165 | alpha: tensor(-347.6495) | beta: tensor(-122.9241)
index: 166 | alpha: tensor(603.7319) | beta: tensor(121.3831)
index: 167 | alpha: tensor(-837.1159) | beta: tensor(-574.3900)
index: 168 | alpha: tensor(24.6307) | beta: tensor(-796.9601)
index: 169 | alpha: tensor(53.3533) | beta: tensor(-16.0263)
index: 170 | alpha: tensor(-185.1322) | beta: tensor(96.5248)
index: 171 | alpha: tensor(-66.8254) | beta: tensor(-90.8420)
index: 172 | alpha: tensor(94.1507) | beta: tensor(-555.9086)
index: 173 | alpha: tensor(-525.0455) | beta: tensor(-52.6862)
index: 174 | alpha: tensor(-99.5285) | beta: tensor(19.4984)
index: 175 | alpha: tensor(547.1356) | beta: tensor(175.7148)
index: 176 | alpha: tensor(81.8196) | beta: tensor(-467.5012)
index: 177 | alpha: tensor(-633.9279) | beta: tensor(-330.2293)
index: 178 | alpha: tensor(-111.0271) | beta: tensor(-387.7879)
index: 179 | alpha: tensor(568.8330) | beta: tensor(400.0087)
index: 180 | alpha: tensor(-466.2805) | beta: tensor(-125.3133)
index: 181 | alpha: tensor(112.8463) | beta: tensor(387.5028)
index: 182 | alpha: tensor(-198.4938) | beta: tensor(205.1830)
index: 183 | alpha: tensor(-184.1169) | beta: tensor(208.8831)
index: 184 | alpha: tensor(-114.8766) | beta: tensor(-440.7760)
index: 185 | alpha: tensor(224.0591) | beta: tensor(337.9455)
index: 186 | alpha: tensor(520.1049) | beta: tensor(147.4058)
index: 187 | alpha: tensor(250.5161) | beta: tensor(-278.0299)
index: 188 | alpha: tensor(92.7657) | beta: tensor(-159.7500)
index: 189 | alpha: tensor(99.1288) | beta: tensor(-211.0064)
index: 190 | alpha: tensor(128.8766) | beta: tensor(645.2924)
index: 191 | alpha: tensor(191.4183) | beta: tensor(237.6417)
index: 192 | alpha: tensor(600.6099) | beta: tensor(-253.4765)
index: 193 | alpha: tensor(-139.4402) | beta: tensor(293.3190)
index: 194 | alpha: tensor(-319.3196) | beta: tensor(149.4888)
index: 195 | alpha: tensor(218.6239) | beta: tensor(144.0081)
index: 196 | alpha: tensor(521.9194) | beta: tensor(355.9746)
index: 197 | alpha: tensor(-59.0425) | beta: tensor(-276.7986)
index: 198 | alpha: tensor(-264.5910) | beta: tensor(-306.4624)
index: 199 | alpha: tensor(-466.3147) | beta: tensor(-248.0728)
index: 200 | alpha: tensor(-118.5223) | beta: tensor(-196.1816)
index: 201 | alpha: tensor(36.3926) | beta: tensor(248.2610)
index: 202 | alpha: tensor(248.7370) | beta: tensor(-134.5499)
index: 203 | alpha: tensor(-16.7666) | beta: tensor(30.4693)
index: 204 | alpha: tensor(139.9332) | beta: tensor(35.2079)
index: 205 | alpha: tensor(116.8003) | beta: tensor(410.4206)
index: 206 | alpha: tensor(-132.3640) | beta: tensor(109.7768)
index: 207 | alpha: tensor(-167.3363) | beta: tensor(255.1017)
index: 208 | alpha: tensor(-164.1863) | beta: tensor(-278.2570)
index: 209 | alpha: tensor(-560.2722) | beta: tensor(-187.6624)
index: 210 | alpha: tensor(-109.3077) | beta: tensor(49.4284)
index: 211 | alpha: tensor(139.5030) | beta: tensor(472.4523)
index: 212 | alpha: tensor(-138.5093) | beta: tensor(-554.9415)
index: 213 | alpha: tensor(462.3124) | beta: tensor(-49.9858)
index: 214 | alpha: tensor(-688.3619) | beta: tensor(-222.8699)
index: 215 | alpha: tensor(-294.2288) | beta: tensor(-299.2778)
index: 216 | alpha: tensor(-66.0108) | beta: tensor(-555.7604)
index: 217 | alpha: tensor(-231.5717) | beta: tensor(77.9807)
index: 218 | alpha: tensor(329.4146) | beta: tensor(-239.0666)
index: 219 | alpha: tensor(207.7111) | beta: tensor(-162.3613)
index: 220 | alpha: tensor(-410.6408) | beta: tensor(195.4356)
index: 221 | alpha: tensor(433.4129) | beta: tensor(-511.4191)
index: 222 | alpha: tensor(-106.9184) | beta: tensor(-213.0401)
index: 223 | alpha: tensor(509.3317) | beta: tensor(420.9495)
index: 224 | alpha: tensor(-380.0234) | beta: tensor(288.7041)
index: 225 | alpha: tensor(494.1917) | beta: tensor(447.8525)
index: 226 | alpha: tensor(896.4965) | beta: tensor(-151.2490)
index: 227 | alpha: tensor(8.6733) | beta: tensor(-258.1767)
index: 228 | alpha: tensor(73.9565) | beta: tensor(97.9020)
index: 229 | alpha: tensor(-280.3212) | beta: tensor(71.5657)
index: 230 | alpha: tensor(296.0760) | beta: tensor(-333.2220)
index: 231 | alpha: tensor(-73.1461) | beta: tensor(-95.2714)
index: 232 | alpha: tensor(-181.8225) | beta: tensor(-210.7853)
index: 233 | alpha: tensor(-5.0726) | beta: tensor(159.6389)
index: 234 | alpha: tensor(626.7166) | beta: tensor(-373.9386)
index: 235 | alpha: tensor(-58.9155) | beta: tensor(362.2147)
index: 236 | alpha: tensor(-44.0161) | beta: tensor(399.1544)
index: 237 | alpha: tensor(120.0379) | beta: tensor(-98.4167)
index: 238 | alpha: tensor(-65.6416) | beta: tensor(-188.2357)
index: 239 | alpha: tensor(154.1313) | beta: tensor(187.7709)
index: 240 | alpha: tensor(113.9361) | beta: tensor(-3.6869)
index: 241 | alpha: tensor(-170.1361) | beta: tensor(67.8275)
index: 242 | alpha: tensor(68.8198) | beta: tensor(-686.4819)
index: 243 | alpha: tensor(518.2602) | beta: tensor(-195.9737)
index: 244 | alpha: tensor(-263.6393) | beta: tensor(-356.6319)
index: 245 | alpha: tensor(-212.3180) | beta: tensor(134.4063)
index: 246 | alpha: tensor(386.7928) | beta: tensor(-108.4692)
index: 247 | alpha: tensor(402.6908) | beta: tensor(-312.7831)
index: 248 | alpha: tensor(-55.9886) | beta: tensor(-82.5674)
index: 249 | alpha: tensor(146.1949) | beta: tensor(-67.3596)
index: 250 | alpha: tensor(331.6237) | beta: tensor(47.7861)
index: 251 | alpha: tensor(163.0124) | beta: tensor(-254.0310)
index: 252 | alpha: tensor(-160.3099) | beta: tensor(134.1357)
index: 253 | alpha: tensor(-149.8085) | beta: tensor(-344.1933)
index: 254 | alpha: tensor(-197.0074) | beta: tensor(299.9363)
index: 255 | alpha: tensor(-546.6909) | beta: tensor(39.7721)
index: 256 | alpha: tensor(-164.4482) | beta: tensor(-219.9871)
index: 257 | alpha: tensor(133.4471) | beta: tensor(161.6139)
index: 258 | alpha: tensor(-140.4120) | beta: tensor(194.7817)
index: 259 | alpha: tensor(-207.9165) | beta: tensor(92.4359)
index: 260 | alpha: tensor(-332.7815) | beta: tensor(-70.0711)
index: 261 | alpha: tensor(-678.3976) | beta: tensor(20.3232)
index: 262 | alpha: tensor(-383.5952) | beta: tensor(-201.3509)
index: 263 | alpha: tensor(316.5221) | beta: tensor(-144.4218)
index: 264 | alpha: tensor(-353.1637) | beta: tensor(170.9221)
index: 265 | alpha: tensor(-25.6894) | beta: tensor(103.3272)
index: 266 | alpha: tensor(-434.9973) | beta: tensor(548.2225)
index: 267 | alpha: tensor(119.2911) | beta: tensor(-43.6890)
index: 268 | alpha: tensor(13.8974) | beta: tensor(215.5111)
index: 269 | alpha: tensor(691.4511) | beta: tensor(243.0143)
index: 270 | alpha: tensor(110.3818) | beta: tensor(270.8066)
index: 271 | alpha: tensor(238.5337) | beta: tensor(742.8111)
index: 272 | alpha: tensor(-178.9887) | beta: tensor(-310.5594)
index: 273 | alpha: tensor(60.1018) | beta: tensor(-276.1313)
index: 274 | alpha: tensor(-135.2739) | beta: tensor(-24.6505)
index: 275 | alpha: tensor(195.1267) | beta: tensor(-354.1717)
index: 276 | alpha: tensor(661.8249) | beta: tensor(-403.3620)
index: 277 | alpha: tensor(-42.5310) | beta: tensor(27.6330)
index: 278 | alpha: tensor(-312.3462) | beta: tensor(199.4764)
index: 279 | alpha: tensor(493.9920) | beta: tensor(-251.7336)
index: 280 | alpha: tensor(-249.5683) | beta: tensor(99.0694)
index: 281 | alpha: tensor(376.9445) | beta: tensor(2.5743)
index: 282 | alpha: tensor(154.4284) | beta: tensor(-749.5905)
index: 283 | alpha: tensor(-65.8934) | beta: tensor(-356.1980)
index: 284 | alpha: tensor(-79.6281) | beta: tensor(-54.6249)
index: 285 | alpha: tensor(-247.8593) | beta: tensor(65.9351)
index: 286 | alpha: tensor(-468.5690) | beta: tensor(237.3133)
index: 287 | alpha: tensor(108.4757) | beta: tensor(165.1879)
index: 288 | alpha: tensor(-707.2863) | beta: tensor(424.4366)
index: 289 | alpha: tensor(-42.6478) | beta: tensor(-101.9737)
index: 290 | alpha: tensor(-59.6616) | beta: tensor(72.7298)
index: 291 | alpha: tensor(63.4050) | beta: tensor(-246.9169)
index: 292 | alpha: tensor(274.7314) | beta: tensor(-164.0209)
index: 293 | alpha: tensor(-638.8661) | beta: tensor(-708.8142)
index: 294 | alpha: tensor(-388.3833) | beta: tensor(430.9984)
index: 295 | alpha: tensor(-37.0517) | beta: tensor(-208.7065)
index: 296 | alpha: tensor(-299.0446) | beta: tensor(403.6170)
index: 297 | alpha: tensor(16.3879) | beta: tensor(88.5191)
index: 298 | alpha: tensor(168.1377) | beta: tensor(-27.5016)
index: 299 | alpha: tensor(76.7448) | beta: tensor(515.3869)
index: 300 | alpha: tensor(116.0710) | beta: tensor(294.2166)
index: 301 | alpha: tensor(482.7467) | beta: tensor(62.1841)
index: 302 | alpha: tensor(230.0112) | beta: tensor(-244.7131)
index: 303 | alpha: tensor(238.1015) | beta: tensor(-36.8030)
index: 304 | alpha: tensor(-186.2212) | beta: tensor(-295.9939)
index: 305 | alpha: tensor(242.5196) | beta: tensor(365.9585)
index: 306 | alpha: tensor(-216.9044) | beta: tensor(364.2641)
index: 307 | alpha: tensor(337.3563) | beta: tensor(-407.5153)
index: 308 | alpha: tensor(-513.7169) | beta: tensor(298.7433)
index: 309 | alpha: tensor(-164.5553) | beta: tensor(409.6697)
index: 310 | alpha: tensor(-483.3584) | beta: tensor(-540.1486)
index: 311 | alpha: tensor(-388.0682) | beta: tensor(473.4029)
index: 312 | alpha: tensor(-399.8923) | beta: tensor(-793.0036)
index: 313 | alpha: tensor(-142.8166) | beta: tensor(-177.1035)
index: 314 | alpha: tensor(-343.2724) | beta: tensor(128.6988)
index: 315 | alpha: tensor(-3.7616) | beta: tensor(-335.4054)
index: 316 | alpha: tensor(-311.3952) | beta: tensor(282.5244)
index: 317 | alpha: tensor(401.8747) | beta: tensor(-213.0955)
index: 318 | alpha: tensor(188.0654) | beta: tensor(1.1845)
index: 319 | alpha: tensor(-389.0319) | beta: tensor(47.3265)
index: 320 | alpha: tensor(253.2753) | beta: tensor(254.0471)
index: 321 | alpha: tensor(-226.0018) | beta: tensor(-671.1318)
index: 322 | alpha: tensor(-190.7752) | beta: tensor(58.0676)
index: 323 | alpha: tensor(424.4028) | beta: tensor(-163.0139)
index: 324 | alpha: tensor(-40.4921) | beta: tensor(-564.3600)
index: 325 | alpha: tensor(-796.6172) | beta: tensor(-380.8007)
index: 326 | alpha: tensor(272.3678) | beta: tensor(51.6157)
index: 327 | alpha: tensor(694.2856) | beta: tensor(-240.9753)
index: 328 | alpha: tensor(150.0191) | beta: tensor(-166.3920)
index: 329 | alpha: tensor(165.8963) | beta: tensor(-84.6316)
index: 330 | alpha: tensor(112.2921) | beta: tensor(2.8970)
index: 331 | alpha: tensor(71.1856) | beta: tensor(-342.1713)
index: 332 | alpha: tensor(-443.0225) | beta: tensor(377.6964)
index: 333 | alpha: tensor(-348.2093) | beta: tensor(-507.2314)
index: 334 | alpha: tensor(-478.5285) | beta: tensor(-230.5791)
index: 335 | alpha: tensor(-291.4612) | beta: tensor(144.6568)
index: 336 | alpha: tensor(40.6857) | beta: tensor(224.5731)
index: 337 | alpha: tensor(-377.2997) | beta: tensor(-97.9533)
index: 338 | alpha: tensor(375.3276) | beta: tensor(99.3058)
index: 339 | alpha: tensor(93.7896) | beta: tensor(-38.4709)
index: 340 | alpha: tensor(-229.2892) | beta: tensor(117.7463)
index: 341 | alpha: tensor(-74.3109) | beta: tensor(-51.9247)
index: 342 | alpha: tensor(-328.7654) | beta: tensor(-329.5365)
index: 343 | alpha: tensor(202.2613) | beta: tensor(-128.0079)
index: 344 | alpha: tensor(-554.0029) | beta: tensor(-264.8636)
index: 345 | alpha: tensor(419.2312) | beta: tensor(280.5667)
index: 346 | alpha: tensor(380.7182) | beta: tensor(-403.2293)
index: 347 | alpha: tensor(-42.2206) | beta: tensor(-161.0726)
index: 348 | alpha: tensor(340.0492) | beta: tensor(82.5101)
index: 349 | alpha: tensor(-218.1228) | beta: tensor(496.5203)
index: 350 | alpha: tensor(-230.6914) | beta: tensor(108.2541)
index: 351 | alpha: tensor(154.8929) | beta: tensor(110.9167)
index: 352 | alpha: tensor(75.8950) | beta: tensor(375.2977)
index: 353 | alpha: tensor(0.9041) | beta: tensor(-29.1716)
index: 354 | alpha: tensor(205.9621) | beta: tensor(-280.8953)
index: 355 | alpha: tensor(-501.8264) | beta: tensor(-17.9303)
index: 356 | alpha: tensor(-118.3396) | beta: tensor(-249.7531)
index: 357 | alpha: tensor(148.7595) | beta: tensor(145.7400)
index: 358 | alpha: tensor(201.8117) | beta: tensor(-510.4276)
index: 359 | alpha: tensor(-292.5282) | beta: tensor(310.6368)
index: 360 | alpha: tensor(-232.4500) | beta: tensor(-149.8077)
index: 361 | alpha: tensor(-56.3256) | beta: tensor(252.3236)
index: 362 | alpha: tensor(377.2491) | beta: tensor(-262.1625)
index: 363 | alpha: tensor(-219.7417) | beta: tensor(-315.4673)
index: 364 | alpha: tensor(-394.2333) | beta: tensor(-539.3148)
index: 365 | alpha: tensor(101.6697) | beta: tensor(-27.9768)
index: 366 | alpha: tensor(295.6522) | beta: tensor(8.8840)
index: 367 | alpha: tensor(-9.8691) | beta: tensor(-411.9929)
index: 368 | alpha: tensor(-47.7944) | beta: tensor(-255.1344)
index: 369 | alpha: tensor(212.3981) | beta: tensor(-56.0242)
index: 370 | alpha: tensor(-393.8351) | beta: tensor(184.2736)
index: 371 | alpha: tensor(155.5316) | beta: tensor(-208.6744)
index: 372 | alpha: tensor(80.6195) | beta: tensor(122.5009)
index: 373 | alpha: tensor(-9.1227) | beta: tensor(538.0145)
index: 374 | alpha: tensor(-166.9138) | beta: tensor(-275.2154)
index: 375 | alpha: tensor(318.6875) | beta: tensor(-335.4539)
index: 376 | alpha: tensor(-657.6641) | beta: tensor(225.8662)
index: 377 | alpha: tensor(-380.7135) | beta: tensor(227.8003)
index: 378 | alpha: tensor(-226.0178) | beta: tensor(634.6989)
index: 379 | alpha: tensor(325.6752) | beta: tensor(-351.8438)
index: 380 | alpha: tensor(-407.5264) | beta: tensor(-481.2566)
index: 381 | alpha: tensor(305.5659) | beta: tensor(-7.1799)
index: 382 | alpha: tensor(-85.9055) | beta: tensor(348.8602)
index: 383 | alpha: tensor(108.2003) | beta: tensor(-230.1070)
index: 384 | alpha: tensor(504.8516) | beta: tensor(543.2915)
index: 385 | alpha: tensor(-33.1399) | beta: tensor(178.7538)
index: 386 | alpha: tensor(340.6907) | beta: tensor(-307.3799)
index: 387 | alpha: tensor(-245.0339) | beta: tensor(436.3453)
index: 388 | alpha: tensor(99.6829) | beta: tensor(95.7458)
index: 389 | alpha: tensor(-81.7733) | beta: tensor(290.7488)
index: 390 | alpha: tensor(-423.5992) | beta: tensor(-230.2244)
index: 391 | alpha: tensor(-123.9526) | beta: tensor(-159.4308)
index: 392 | alpha: tensor(-30.0249) | beta: tensor(8.8333)
index: 393 | alpha: tensor(-399.9939) | beta: tensor(-379.7474)
index: 394 | alpha: tensor(69.6002) | beta: tensor(338.0919)
index: 395 | alpha: tensor(146.3863) | beta: tensor(466.7140)
index: 396 | alpha: tensor(-54.0445) | beta: tensor(-196.9691)
index: 397 | alpha: tensor(291.0749) | beta: tensor(415.3133)
index: 398 | alpha: tensor(-602.9887) | beta: tensor(-116.5840)
index: 399 | alpha: tensor(-59.5160) | beta: tensor(317.6062)
index: 400 | alpha: tensor(80.5051) | beta: tensor(-231.6370)
index: 401 | alpha: tensor(241.1376) | beta: tensor(-479.3189)
index: 402 | alpha: tensor(-174.2790) | beta: tensor(289.1308)
index: 403 | alpha: tensor(220.9262) | beta: tensor(-109.3848)
index: 404 | alpha: tensor(98.7870) | beta: tensor(-267.9368)
index: 405 | alpha: tensor(-16.4509) | beta: tensor(10.0667)
index: 406 | alpha: tensor(276.6943) | beta: tensor(-91.8507)
index: 407 | alpha: tensor(195.0573) | beta: tensor(498.5777)
index: 408 | alpha: tensor(1.5266) | beta: tensor(675.5605)
index: 409 | alpha: tensor(-329.4788) | beta: tensor(78.1618)
index: 410 | alpha: tensor(-4.3561) | beta: tensor(-110.9660)
index: 411 | alpha: tensor(-254.8243) | beta: tensor(338.0176)
index: 412 | alpha: tensor(-201.9214) | beta: tensor(-274.8942)
index: 413 | alpha: tensor(96.7409) | beta: tensor(121.4664)
index: 414 | alpha: tensor(-268.4978) | beta: tensor(-87.5512)
index: 415 | alpha: tensor(1.1328) | beta: tensor(-218.8405)
index: 416 | alpha: tensor(71.8431) | beta: tensor(102.5472)
index: 417 | alpha: tensor(-333.7213) | beta: tensor(202.8392)
index: 418 | alpha: tensor(19.6250) | beta: tensor(542.8157)
index: 419 | alpha: tensor(-333.6108) | beta: tensor(552.9610)
index: 420 | alpha: tensor(-67.6457) | beta: tensor(-679.3557)
index: 421 | alpha: tensor(251.3518) | beta: tensor(100.8131)
index: 422 | alpha: tensor(293.2778) | beta: tensor(-293.4082)
index: 423 | alpha: tensor(337.5225) | beta: tensor(-39.0203)
index: 424 | alpha: tensor(302.4808) | beta: tensor(30.1141)
index: 425 | alpha: tensor(-6.0839) | beta: tensor(-241.2761)
index: 426 | alpha: tensor(419.1415) | beta: tensor(-432.2838)
index: 427 | alpha: tensor(-370.6875) | beta: tensor(306.3484)
index: 428 | alpha: tensor(771.7524) | beta: tensor(500.8555)
index: 429 | alpha: tensor(125.7668) | beta: tensor(-108.4057)
index: 430 | alpha: tensor(744.8840) | beta: tensor(-175.4764)
index: 431 | alpha: tensor(-333.2534) | beta: tensor(113.7371)
index: 432 | alpha: tensor(-555.6030) | beta: tensor(-343.0692)
index: 433 | alpha: tensor(-97.7192) | beta: tensor(-139.7079)
index: 434 | alpha: tensor(4.2104) | beta: tensor(-177.0169)
index: 435 | alpha: tensor(263.1772) | beta: tensor(-340.5447)
index: 436 | alpha: tensor(-0.5374) | beta: tensor(213.2591)
index: 437 | alpha: tensor(-228.1222) | beta: tensor(-26.6614)
index: 438 | alpha: tensor(478.8295) | beta: tensor(-15.7484)
index: 439 | alpha: tensor(352.7077) | beta: tensor(345.3010)
index: 440 | alpha: tensor(-236.1851) | beta: tensor(-79.4888)
index: 441 | alpha: tensor(93.7599) | beta: tensor(-54.4807)
index: 442 | alpha: tensor(167.8317) | beta: tensor(-545.1718)
index: 443 | alpha: tensor(-867.0198) | beta: tensor(236.5933)
index: 444 | alpha: tensor(441.1665) | beta: tensor(836.7850)
index: 445 | alpha: tensor(81.9887) | beta: tensor(405.3568)
index: 446 | alpha: tensor(102.6995) | beta: tensor(142.0813)
index: 447 | alpha: tensor(110.7140) | beta: tensor(55.8218)
index: 448 | alpha: tensor(-400.0708) | beta: tensor(-126.1912)
index: 449 | alpha: tensor(-17.5037) | beta: tensor(101.0422)
index: 450 | alpha: tensor(-47.4457) | beta: tensor(-113.7148)
index: 451 | alpha: tensor(-121.8680) | beta: tensor(417.6931)
index: 452 | alpha: tensor(-209.7801) | beta: tensor(254.6367)
index: 453 | alpha: tensor(245.2615) | beta: tensor(-383.9518)
index: 454 | alpha: tensor(98.5530) | beta: tensor(104.4786)
index: 455 | alpha: tensor(-786.1419) | beta: tensor(480.3913)
index: 456 | alpha: tensor(-147.3143) | beta: tensor(199.3137)
index: 457 | alpha: tensor(437.6915) | beta: tensor(176.4892)
index: 458 | alpha: tensor(332.6019) | beta: tensor(-806.2597)
index: 459 | alpha: tensor(21.8787) | beta: tensor(608.0240)
index: 460 | alpha: tensor(254.1735) | beta: tensor(204.6718)
index: 461 | alpha: tensor(44.8402) | beta: tensor(-271.4605)
index: 462 | alpha: tensor(-138.8948) | beta: tensor(373.3802)
index: 463 | alpha: tensor(343.5590) | beta: tensor(-52.3700)
index: 464 | alpha: tensor(-94.4366) | beta: tensor(-469.3587)
index: 465 | alpha: tensor(-45.1689) | beta: tensor(322.3189)
index: 466 | alpha: tensor(14.5029) | beta: tensor(-15.8604)
index: 467 | alpha: tensor(-178.4107) | beta: tensor(309.2284)
index: 468 | alpha: tensor(-260.4605) | beta: tensor(350.3957)
index: 469 | alpha: tensor(-71.3811) | beta: tensor(-454.3027)
index: 470 | alpha: tensor(-688.1609) | beta: tensor(-340.2725)
index: 471 | alpha: tensor(-372.3086) | beta: tensor(300.4828)
index: 472 | alpha: tensor(72.2966) | beta: tensor(30.8140)
index: 473 | alpha: tensor(-146.7562) | beta: tensor(81.0578)
index: 474 | alpha: tensor(-89.8894) | beta: tensor(-211.6386)
index: 475 | alpha: tensor(204.0957) | beta: tensor(106.2579)
index: 476 | alpha: tensor(-185.7765) | beta: tensor(-152.6884)
index: 477 | alpha: tensor(-125.8587) | beta: tensor(-102.2100)
index: 478 | alpha: tensor(-71.6389) | beta: tensor(244.4980)
index: 479 | alpha: tensor(56.8839) | beta: tensor(358.0616)
index: 480 | alpha: tensor(159.4951) | beta: tensor(-30.3345)
index: 481 | alpha: tensor(-170.1685) | beta: tensor(188.8311)
index: 482 | alpha: tensor(-609.3884) | beta: tensor(85.2079)
index: 483 | alpha: tensor(-51.6061) | beta: tensor(-227.5923)
index: 484 | alpha: tensor(-44.3321) | beta: tensor(-32.6685)
index: 485 | alpha: tensor(147.9208) | beta: tensor(31.6044)
index: 486 | alpha: tensor(359.5168) | beta: tensor(154.1817)
index: 487 | alpha: tensor(-201.7964) | beta: tensor(71.9791)
index: 488 | alpha: tensor(-375.2611) | beta: tensor(-312.6996)
index: 489 | alpha: tensor(-531.1518) | beta: tensor(145.3253)
index: 490 | alpha: tensor(223.1391) | beta: tensor(-500.5743)
index: 491 | alpha: tensor(-624.4661) | beta: tensor(223.8724)
index: 492 | alpha: tensor(268.5523) | beta: tensor(106.0525)
index: 493 | alpha: tensor(-152.8450) | beta: tensor(-571.3979)
index: 494 | alpha: tensor(12.1359) | beta: tensor(6.9221)
index: 495 | alpha: tensor(192.3008) | beta: tensor(68.2995)
index: 496 | alpha: tensor(-280.0969) | beta: tensor(485.9623)
index: 497 | alpha: tensor(53.6417) | beta: tensor(136.1379)
index: 498 | alpha: tensor(-84.3363) | beta: tensor(-480.8346)
index: 499 | alpha: tensor(-251.7196) | beta: tensor(-72.4205)
# Sampled with sigmoid(alpha.xa + beta.xs)
# for chain, samples in pruned_hmc_sample_chains.items():
for chain, samples in hmc_sample_chains.items():
samples= dict(map(lambda param: (param, torch.tensor(samples.get(param))), samples.keys()))# np array to tensors
print(chain, "Sample count: ", len(samples["alpha"]))
title= "parameter distribution for : %s"%(chain)
fig = ff.create_distplot(list(map(lambda x:x.numpy(), samples.values())), list(samples.keys()))
fig.update_layout(title=title, xaxis_title="parameter values", yaxis_title="density", legend_title="parameters")
fig.show()
print("Alpha Q(0.5) :%s | Beta Q(0.5) :%s\n"%(torch.quantile(samples["alpha"], 0.5), torch.quantile(samples["beta"], 0.5)))
chain_0 Sample count: 10000
Alpha Q(0.5) :tensor(-0.2156) | Beta Q(0.5) :tensor(0.1789)
chain_1 Sample count: 10000
Alpha Q(0.5) :tensor(-0.2155) | Beta Q(0.5) :tensor(0.1789)
# model with Pij as torch.exp()
hmc_sample_chains_, hmc_chain_diagnostics_ = get_hmc_n_chains(DogsModel, x_avoidance, x_shocked, y, num_chains=2, sample_count = 900)
Sample: 100%|██████████| 10090/10090 [01:31, 109.98it/s, step size=6.30e-03, acc. prob=0.946]
Sample: 100%|██████████| 10090/10090 [00:32, 307.69it/s, step size=1.83e-02, acc. prob=0.753]
Total time: 125.14200592041016
# Sampled with torch.exp(alpha.xa + beta.xs)
# for chain, samples in pruned_hmc_sample_chains.items():
for chain, samples in hmc_sample_chains_.items():
samples= dict(map(lambda param: (param, torch.tensor(samples.get(param))), samples.keys()))# np array to tensors
print(chain, "Sample count: ", len(samples["alpha"]))
title= "parameter distribution for : %s"%(chain)
fig = ff.create_distplot(list(map(lambda x:x.numpy(), samples.values())), list(samples.keys()))
fig.update_layout(title=title, xaxis_title="parameter values", yaxis_title="density", legend_title="parameters")
fig.show()
print("Alpha Q(0.5) :%s | Beta Q(0.5) :%s\n"%(torch.quantile(samples["alpha"], 0.5), torch.quantile(samples["beta"], 0.5)))
chain_0 Sample count: 10000
Alpha Q(0.5) :tensor(-0.1940) | Beta Q(0.5) :tensor(-0.0073)
chain_1 Sample count: 10000
Alpha Q(0.5) :tensor(-0.1938) | Beta Q(0.5) :tensor(-0.0073)
hmc_sample_chains holds sampled MCMC values as {"Chain_0": {alpha [-0.20020795, -0.1829252, -0.18054989 . .,], "beta": {}. .,}, "Chain_1": {alpha [-0.20020795, -0.1829252, -0.18054989 . .,], "beta": {}. .,}. .}
5. Diagnosing the computational approximation¶
Just like any numerical technique, no matter how good the theory is or how robust the implementation is, it is always a good idea to check if indeed the samples drawn are reasonable. In the ideal situation, we expect the samples drawm by the sampler to be independant, and identically distributed (i.i.d) as the posterior distribution. In practice, this is far from true as MCMC itself is an approxmate technique and a lot can go wrong. In particular, chains may not have converged or samples are very correlated.
We can use both visual and more formal statistical techniques to inspect the quality of the fit (not the model fit to the data, but how well the appximation is, having accepted the model class for the data at hand) by treating chains as time-series data, and that we can run several chains in parallel. We precisely do that next.
Following snippet allows plotting Parameter vs. Chain matrix and optionally saving the dataframe.
beta_chain_matrix_df = pd.DataFrame(hmc_sample_chains)
beta_chain_matrix_df
| chain_0 | chain_1 | chain_2 | chain_3 | |
|---|---|---|---|---|
| alpha | [-0.18247911, -0.18247911, -0.177892, -0.25068... | [-0.24699849, -0.23552026, -0.22051498, -0.216... | [-0.2489077, -0.25114396, -0.23010185, -0.2127... | [-0.23833714, -0.22708505, -0.22911163, -0.228... |
| beta | [0.15564732, 0.15564732, 0.15665944, 0.1957288... | [0.20732063, 0.19918688, 0.20442879, 0.1519572... | [0.19890349, 0.20747152, 0.19307034, 0.1772510... | [0.17131813, 0.1978431, 0.19519521, 0.19493334... |
# Unpruned sample chains
base.save_parameter_chain_dataframe(beta_chain_matrix_df, "data/dogs_parameter_chain_matrix.csv")
Saved at 'data/dogs_parameter_chain_matrix.csv'
Sample chains mixing for Normal priors¶
Following plots chains of samples for alpha & beta parameters
base.plot_chains(beta_chain_matrix_df)
Auto-correlation plots for sample chains with Normal priors¶
base.autocorrelation_plots(beta_chain_matrix_df)
For alpha, thining factor for chain_0 is 3, chain_1 is 3, chain_2 is 3, chain_3 is 3
for beta, thinin factor for chain_0 is 3, chain_1 is 3, chain_2 is 3, chain_3 is 3
thining_dict = {"chain_0": {"alpha":4, "beta":4}, "chain_1": {"alpha":4, "beta":4},
"chain_2": {"alpha":4, "beta":4}, "chain_3": {"alpha":4, "beta":4}}
pruned_hmc_sample_chains = base.prune_hmc_samples(hmc_sample_chains, thining_dict)
-------------------------
Original sample counts for 'chain_0' parameters: {'alpha': (10000,), 'beta': (10000,)}
Thining factors for 'chain_0' parameters: {'alpha': 4, 'beta': 4}
Post thining sample counts for 'chain_0' parameters: {'alpha': (2500,), 'beta': (2500,)}
-------------------------
Original sample counts for 'chain_1' parameters: {'alpha': (10000,), 'beta': (10000,)}
Thining factors for 'chain_1' parameters: {'alpha': 4, 'beta': 4}
Post thining sample counts for 'chain_1' parameters: {'alpha': (2500,), 'beta': (2500,)}
-------------------------
Original sample counts for 'chain_2' parameters: {'alpha': (10000,), 'beta': (10000,)}
Thining factors for 'chain_2' parameters: {'alpha': 4, 'beta': 4}
Post thining sample counts for 'chain_2' parameters: {'alpha': (2500,), 'beta': (2500,)}
-------------------------
Original sample counts for 'chain_3' parameters: {'alpha': (10000,), 'beta': (10000,)}
Thining factors for 'chain_3' parameters: {'alpha': 4, 'beta': 4}
Post thining sample counts for 'chain_3' parameters: {'alpha': (2500,), 'beta': (2500,)}
Gelman-Rubin statistic for Normal priors¶
grubin_values = base.gelman_rubin_stats(pruned_hmc_sample_chains)
Gelmen-rubin for 'param' alpha all chains is: 0.9997
Gelmen-rubin for 'param' beta all chains is: 0.9997
# Following diagnostic table is for Un-pruned chains from sampler.
base.get_chain_diagnostics(hmc_chain_diagnostics)
| acceptance rate | divergences | metric_values | |||
|---|---|---|---|---|---|
| parameters | chain | metric | |||
| beta | chain_0 | n_eff | 0.9765 | [] | 4191.906250 |
| r_hat | 0.9765 | [] | 1.000613 | ||
| chain_1 | n_eff | 0.9891 | [] | 4057.659424 | |
| r_hat | 0.9891 | [] | 1.000336 | ||
| chain_2 | n_eff | 0.9621 | [] | 4745.110352 | |
| r_hat | 0.9621 | [] | 0.999936 | ||
| chain_3 | n_eff | 0.9722 | [] | 3728.569092 | |
| r_hat | 0.9722 | [] | 1.000023 | ||
| alpha | chain_0 | n_eff | 0.9765 | [] | 4495.870605 |
| r_hat | 0.9765 | [] | 1.000639 | ||
| chain_1 | n_eff | 0.9891 | [] | 4366.684082 | |
| r_hat | 0.9891 | [] | 1.000021 | ||
| chain_2 | n_eff | 0.9621 | [] | 5142.791504 | |
| r_hat | 0.9621 | [] | 0.999903 | ||
| chain_3 | n_eff | 0.9722 | [] | 4875.547363 | |
| r_hat | 0.9722 | [] | 0.999976 |
Based on simple multiple line plots, we can see that, in this run, chain_3 is behaving differently than the remaining chains. It may be due to really a different initialization. Otherwise, all chains seem to mix well. Therefore, we drop chain_3 from analysis. However, we need to be cautious about dropping, and we should check what is its effect on the actual predictions – since sometimes, even though parameters can look very different numerically, they may have very little effect on the likelihood. Neverthless, it implies that either something is not right about the chain or the model is operating at the edge.
Descriptive summaries¶
Following outputs the summary of required statistics such as "mean", "std", "Q(0.25)", "Q(0.50)", "Q(0.75)", select names of statistic metric from given list to view values
#chain results Pruned after ACF plots
beta_chain_matrix_df = pd.DataFrame(pruned_hmc_sample_chains)
base.summary(beta_chain_matrix_df)
Select any value
We can also report the 5-point Summary Statistics (mean, Q1-Q4, Std, ) as tabular data per chain and save the dataframe
fit_df = pd.DataFrame()
for chain, values in pruned_hmc_sample_chains.items():
param_df = pd.DataFrame(values)
param_df["chain"]= chain
fit_df= pd.concat([fit_df, param_df], axis=0)
# fit_df.to_csv("data/dogs_classification_hmc_samples.csv", index=False)
fit_df.head(3)
| alpha | beta | chain | |
|---|---|---|---|
| 0 | -0.182479 | 0.155647 | chain_0 |
| 1 | -0.246963 | 0.211808 | chain_0 |
| 2 | -0.212009 | 0.191411 | chain_0 |
base.save_parameter_chain_dataframe(fit_df, "data/dogs_classification_hmc_samples.csv")
Saved at 'data/dogs_classification_hmc_samples.csv'
# Use following to load data once the results from pyro sampling operation are saved offline
load_button= base.build_upload_button()
# Use following to load data once the results from pyro sampling operation are
# saved offline
if load_button.value:
fit_df = base.load_parameter_chain_dataframe(load_button)
fit_df.head(3)
| alpha | beta | chain | |
|---|---|---|---|
| 0 | -0.182479 | 0.155647 | chain_0 |
| 1 | -0.246963 | 0.211808 | chain_0 |
| 2 | -0.212009 | 0.191411 | chain_0 |
Following outputs the similar summary of required statistics such as "mean", "std", "Q(0.25)", "Q(0.50)", "Q(0.75)", but in a slightly different format, given a list of statistic names
base.summary(fit_df, layout =2)
Select any value
Following plots sampled parameters values as Boxplots with M parameters side by side on x axis for each of the N chains
Pass the list of M parameters and list of N chains, with plot_interactive as True or False to choose between Plotly or Seaborn
parameters= ["alpha", "beta"]# All parameters for given model
chains= fit_df["chain"].unique()# Number of chains sampled for given model
# Use plot_interactive=False for Normal seaborn plots offline
base.plot_parameters_for_n_chains(fit_df, chains=['chain_0', 'chain_1', 'chain_2', 'chain_3'], parameters=parameters, plot_interactive=True)
Following plots the joint distribution of pair of each parameter sampled values for all chains
base.plot_joint_distribution(fit_df, parameters)
Pyro -- alpha Vs. beta
Following plots the Pairplot distribution of each parameter with every other parameter’s sampled values
sns.pairplot(data=fit_df, hue= "chain");
Based on all above summaries both visual and descriptive, chain_2 seemed problematics, and it is very clear that \(\alpha, \beta <0\) with almost certainly.
TBD: Converence Statsitics like Gelman-Rubin has to be implemented.
6. Sensitivity Analysis¶
Posterior Predictive Checking (PPE) helps examine the fit of a model to real data, as the parameter drawn for simulating conditions & regions of interests come from the posterior distribution. While PPE incorporates model uncertainly (by averaring over all possible models), we take a simpler route to begin with, which is to, sample the \(\alpha, \beta\) pair that is very plausible in the posterior (eg. the poster means), and simulate data from under this particular generative model.
posterior_parameters_pairs_c1= pruned_hmc_sample_chains.get('chain_0')
posterior_parameters_pairs_c1 = list(zip(*list(posterior_parameters_pairs_c1.values())))
print("total posterior samples count in chain:", len(posterior_parameters_pairs_c1), " sample example: ", posterior_parameters_pairs_c1[:2])
total posterior samples count in chain: 2500 sample example: [(-0.18247911, 0.15564732), (-0.24696335, 0.21180753)]
# simulated_data_given_pair_posterior= simulate_observations_given_param(num_dogs=30, num_trials=24, parameter_pair_list= posterior_parameters_pairs_c1)#, print_logs=1
simulated_data_given_pair_posterior= base.simulate_observations_given_param(init_obs=0, num_dogs=30, num_trials=24, parameter_pair_list= posterior_parameters_pairs_c1)#, print_logs=1
print("Number of datasets/posterior pairs generated: ", simulated_data_given_pair_posterior.shape[0])
Total execution time: 166.57034182548523
Number of datasets/posterior pairs generated: 2500
simulated_data_given_pair_posterior_flattened = np.reshape(simulated_data_given_pair_posterior, (-1, 25))
arr1 = np.mean(dogs_data["Y"], axis=0)# Original
arr2=np.mean(simulated_data_given_pair_flattened, axis=0)# Priors
arr3=np.mean(simulated_data_given_pair_posterior_flattened, axis=0)# Posterior
original_plus_simulated_data_plus_posterior= np.concatenate([arr1.reshape((1, -1)), arr2.reshape((1, -1)), arr3.reshape((1, -1))])
print("respective shapes of original data: %s, data simulated from prior: %s, data simulated from posterior: %s and concatenated arrays: %s"%(arr1.shape, arr2.shape, arr3.shape, original_plus_simulated_data_plus_posterior.shape))
respective shapes of original data: (25,), data simulated from prior: (25,), data simulated from posterior: (25,) and concatenated arrays: (3, 25)
base.plot_original_y(original_plus_simulated_data_plus_posterior, ylabel='Probability of avoidance at trial j [all original & simulated prior data]')
print("\n\nHere 'Dog 1' corresponds to Original data, 'Dog 2' corresponds to data simulated from prior & 'Dog 3' corresponds to data simulated from posterior")
Here 'Dog 1' corresponds to Original data, 'Dog 2' corresponds to data simulated from prior & 'Dog 3' corresponds to data simulated from posterior
7. Model Comparison¶
More often than not, there may be many plausible models that can explain the data. Sometime, the modeling choice is based on domain knowledge. Sometime it is out of comptational conveninece. Latter is the case with the choice of priors. One way to consider different models is by eliciting different prior distributions.
As long as the sampling distribtion is same, one can use Deviance Information Criterion (DIC) to guide model comparison.
Deviance Information Criterion¶
DIC is computed as follows
\(D(\alpha,\beta) = -2\ \sum_{i=1}^{n} \log P\ (y_{i}\ /\ \alpha,\beta)\)
\(\log P\ (y_{i}\ /\ \alpha,\beta)\) is the log likehood of shocks/avoidances observed given parameter \(\alpha,\beta\), this expression expands as follows:
Using $D(\alpha,\beta)$ to Compute DIC
\(\overline D(\alpha,\beta) = \frac{1}{T} \sum_{t=1}^{T} D(\alpha,\beta)\)
\(\overline \alpha = \frac{1}{T} \sum_{t=1}^{T}\alpha_{t}\\\) \(\overline \beta = \frac{1}{T} \sum_{t=1}^{T}\beta_{t}\)
\(D(\overline\alpha,\overline\beta) = -2\ \sum_{i=1}^{30}[ y_{i}\ (\overline\alpha Xa_{i}\ +\overline\beta\ Xs_{i}) + \ (1-y_{i})\log\ (1\ -\ e^{(\overline\alpha Xa_{i}\ +\overline\beta\ Xs_{i})})]\)
Therefore finally
\(DIC\ =\ 2\ \overline D(\alpha,\beta)\ -\ D(\overline\alpha,\overline\beta)\)
Following method computes deviance value given parameters `alpha & beta`
#launch docstring for calculate_deviance_given_param
#launch docstring for calculate_mean_deviance
Following method computes deviance information criterion for a given bayesian model & chains of sampled parameters alpha & beta
#launch docstring for DIC
#launch docstring for compare_DICs_given_model
Define alternate model with different priors¶
The following model is defined in the same manner using Pyro as per the following expression of generative model for this dataset, just with modification of prior distribution to Uniform rather than Normal as follows:
Instead of considering Normal priors of \(\alpha\) and \(\beta\), we consider uniform priors, i.e., \(prior\ \alpha\) ~ \(U(-30.79, 30.79)\), \(\beta\) ~ \(U(-30.79, 30.79)\)
# # Dogs model with uniform prior
#launch docstring for DogsModelUniformPrior
DogsModelUniformPrior= base.DogsModelUniformPrior
DogsModelUniformPrior
<function __main__.DogsModelUniformPrior(x_avoidance, x_shocked, y)>
hmc_sample_chains_uniform_prior, hmc_sample_chains_uniform_diagnostics= base.get_hmc_n_chains(DogsModelUniformPrior, x_avoidance, x_shocked, y, num_chains=4, sample_count= 900)
Sample: 100%|██████████| 11000/11000 [01:47, 102.43it/s, step size=3.80e-02, acc. prob=0.926]
Sample: 100%|██████████| 11000/11000 [02:06, 86.70it/s, step size=4.14e-02, acc. prob=0.909]
Sample: 100%|██████████| 11000/11000 [01:50, 99.67it/s, step size=3.88e-02, acc. prob=0.925]
Sample: 100%|██████████| 11000/11000 [02:00, 91.57it/s, step size=3.36e-02, acc. prob=0.947]
Total time: 465.27906799316406
Sample chains mixing for Uniform priors¶
Following plots chains of samples for alpha & beta parameters with uniform priors
beta_chain_matrix_uniform_df = pd.DataFrame(hmc_sample_chains_uniform_prior)
base.plot_chains(beta_chain_matrix_uniform_df)
Auto-correlation plots for sample chains with Uniform priors¶
base.autocorrelation_plots(beta_chain_matrix_uniform_df)
thining_dict_uniform = {"chain_0": {"alpha":7, "beta":7}, "chain_1": {"alpha":7, "beta":7},
"chain_2": {"alpha":7, "beta":7}, "chain_3": {"alpha":7, "beta":7}}
pruned_hmc_sample_chains_uniform_prior = base.prune_hmc_samples(hmc_sample_chains_uniform_prior, thining_dict_uniform)
-------------------------
Original sample counts for 'chain_0' parameters: {'alpha': (10000,), 'beta': (10000,)}
Thining factors for 'chain_0' parameters: {'alpha': 7, 'beta': 7}
Post thining sample counts for 'chain_0' parameters: {'alpha': (1429,), 'beta': (1429,)}
-------------------------
Original sample counts for 'chain_1' parameters: {'alpha': (10000,), 'beta': (10000,)}
Thining factors for 'chain_1' parameters: {'alpha': 7, 'beta': 7}
Post thining sample counts for 'chain_1' parameters: {'alpha': (1429,), 'beta': (1429,)}
-------------------------
Original sample counts for 'chain_2' parameters: {'alpha': (10000,), 'beta': (10000,)}
Thining factors for 'chain_2' parameters: {'alpha': 7, 'beta': 7}
Post thining sample counts for 'chain_2' parameters: {'alpha': (1429,), 'beta': (1429,)}
-------------------------
Original sample counts for 'chain_3' parameters: {'alpha': (10000,), 'beta': (10000,)}
Thining factors for 'chain_3' parameters: {'alpha': 7, 'beta': 7}
Post thining sample counts for 'chain_3' parameters: {'alpha': (1429,), 'beta': (1429,)}
Gelman-Rubin statistic for Uniform priors¶
grubin_values_uniform = base.gelman_rubin_stats(pruned_hmc_sample_chains_uniform_prior)
Gelmen-rubin for 'param' alpha all chains is: 0.9993
Gelmen-rubin for 'param' beta all chains is: 0.9996
compute & compare deviance information criterion for a multiple bayesian models¶
base.compare_DICs_given_model(x_avoidance, x_shocked, y, Dogs_normal_prior= pruned_hmc_sample_chains, Dogs_uniform_prior= pruned_hmc_sample_chains_uniform_prior)
______________________________
For model : Dogs_normal_prior
. . .DIC for chain_0: 472.935
. . .DIC for chain_1: 472.774
. . .DIC for chain_2: 472.948
. . .DIC for chain_3: 472.849
. .Mean Deviance information criterion for all chains: 472.876
______________________________
For model : Dogs_uniform_prior
. . .DIC for chain_0: 625.299
. . .DIC for chain_1: 625.173
. . .DIC for chain_2: 625.596
. . .DIC for chain_3: 625.659
. .Mean Deviance information criterion for all chains: 625.432
The DIC values are very close, so we don’t anticipate substantially different fits. This is largely because, both priors are flat. However, if were to follow the rule book, we had to pick a model with the smallest DIC. In that case, we have to pick Normal Priors over Uniform Priors.
8. Inference & Analysis¶
Alright, we have a model, and we are reasonable sure about the fit (both numerical and conceptual), but so what? The purpose of model building is to use these models as probing devices. That is, using the models can we answer some questions about the reality that these models have abstracted.
We choose model with Normal Prior, and pick samples from one particular chain of HMC samples say chain_3
for chain, samples in pruned_hmc_sample_chains.items():
samples= dict(map(lambda param: (param, torch.tensor(samples.get(param))), samples.keys()))# np array to tensors
print(chain, "Sample count: ", len(samples["alpha"]))
chain_0 Sample count: 2500
chain_1 Sample count: 2500
chain_2 Sample count: 2500
chain_3 Sample count: 2500
Plot density for parameters from chain_3 to visualise the spread of sample values from that chain
title= "parameter distribution for : %s"%(chain)
fig = ff.create_distplot(list(map(lambda x:x.numpy(), samples.values())), list(samples.keys()))
fig.update_layout(title=title, xaxis_title="parameter values", yaxis_title="density", legend_title="parameters")
fig.show()
print("Alpha Q(0.5) :%s | Beta Q(0.5) :%s"%(torch.quantile(samples["alpha"], 0.5), torch.quantile(samples["beta"], 0.5)))
Alpha Q(0.5) :tensor(-0.2148) | Beta Q(0.5) :tensor(0.1786)
Plot density & contours for both parameters from chain_3 to visualise the joint distribution & region of interest
#Choosing samples from chain 3
chain_samples_df= fit_df[fit_df["chain"]==chain].copy()# chain is 'chain_3'
alpha= chain_samples_df["alpha"].tolist()
beta= chain_samples_df["beta"].tolist()
colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)', (1, 1, 0.2), (0.98,0.98,0.98)]
fig = ff.create_2d_density(alpha, beta, colorscale=colorscale, hist_color='rgb(255, 255, 150)', point_size=4, title= "alpha beta joint density plot")
fig.update_layout( xaxis_title="x (alpha)", yaxis_title="y (beta)")
fig.show()
Note: The distribution of alpha values are significantly offset to the left from beta values, by almost 13 times; Thus for any given input observation of avoidances or shocks, the likelihood of getting shocked is more influenced by small measure of avoidance than by getting shocked.
Observations:¶
On observing the joint distribution of \(\alpha, \beta\), we note that \(\beta > \alpha\) and \(\beta\) is closer to zero. Here, \(\beta\) can be interpreted as learning ability, i.e., the ability of a dog to learn from shock experiences. The increase in number of shocks barely raises the probability of non-avoidance (value of 𝜋𝑗) with little amount. Unless the trials & shocks increase considerably large in progression, it doesn’t mellow down well and mostly stays around 0.9.
However, it is not the case with \(\alpha, \alpha\) is more negative & farthest from ‘zero’. It imparts a significant decline in non-avoidance (𝜋𝑗) even for few instances where dog avoids the shock; therefore \(\alpha\) can be interpreted as retention ability i.e., the ability to retain the learning from previous shock experiences.
print(chain_samples_df["alpha"].describe(),"\n\n", chain_samples_df["beta"].describe())
count 2500.000000
mean -0.215691
std 0.016598
min -0.280845
25% -0.226861
50% -0.214832
75% -0.204219
max -0.162974
Name: alpha, dtype: float64
count 2500.000000
mean 0.179158
std 0.020163
min 0.121527
25% 0.164853
50% 0.178601
75% 0.192828
max 0.245223
Name: beta, dtype: float64
From the contour plot above following region in posterior distribution seems highly plausible for parameters:
For alpha,
-0.2 < alpha < -0.19For beta
-0.0075 < beta < -0.0055
Let us look at \(\frac{\alpha}{\beta}\) as a proxy to see which of the two (learning ability and _retention_ability) are domimant.
We are using \(\frac{\alpha}{\beta}\) as a probing device to answer that question, and similar quantities can be defined. With MCMC samples available, we can get posterior probabilties of any function of the model parameters (here \(\alpha, \beta\). Say, we can be interested in the \(E(\frac{\alpha}{\beta})\) or \(P(\frac{\alpha}{\beta}<1)\).
The latter quantity can be estimate by the Monte Carlo average as follows: \(P(\frac{\alpha}{\beta}>1) = \frac{1}{n}\sum_{t=1}^{n} I(\alpha < \beta)\), i.e, the fraction of times \(\alpha < \beta\).
x1 = chain_samples_df["alpha"].to_numpy()
x2 = chain_samples_df["beta"].to_numpy()
p = np.mean(x1<x2)
print(p)
1.0
So, the posterior evident for retention ability outweigting learning abilty is overwhelming.